package utilities.tcpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import utilities.tcpserver.events.event;

public class session 
	extends utilities.events.dispatcher
	implements Runnable
{
	private boolean running;
	private InputStreamReader stream;
	private PrintWriter writer;
	private BufferedReader reader;
	
	protected Socket socket;
	
	protected String read()
	{
		String message = null;
		try {
			message = reader.readLine();
		} catch(IOException error) {}
		
		return message;
	}
	
	public session(Socket socket)
	{
		this.socket = socket;
		
		try {
			stream = new InputStreamReader(socket.getInputStream());
			writer = new PrintWriter(socket.getOutputStream());
		} catch(IOException error) {}
		
		reader = new BufferedReader(stream);
	}
	
	public Socket get()
	{
		return socket;
	}
	
	public void write(String message)
	{
		try {
			writer.println(message + '\0');
			writer.flush();
		} catch(Error e) {}
	}
	
	public void run()
	{
		running = true;
		while(running == true)
		{
			String message = read();
			
			if (message == null)
				close();
			else
				fireEvent(new event(this, message.trim(), event.EventCodes.MESSAGE_RECIVED));
		}
	}
	
	public void close()
	{
		running = false;
		
		fireEvent(new event(this, this, event.EventCodes.SESSION_CLOSED));
		
		try {
			socket.close();
			stream.close();
			reader.close();
			writer.close();
		} catch(IOException e) {}
	}
}
